package com.example.bankmanage.Common;/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


import com.alibaba.ttl.TransmittableThreadLocal;
import com.alibaba.ttl.TtlCallable;
import com.alibaba.ttl.TtlRunnable;
import com.alibaba.ttl.threadpool.TtlExecutors;
import com.example.bankmanage.Common.UserInfoDTO;
import lombok.extern.slf4j.Slf4j;

import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;

/**
 * 用户上下文
 * 公众号：马丁玩编程，回复：加群，添加马哥微信（备注：link）获取项目资料
 */
@Slf4j
public final class UserContext {

    private static final ThreadLocal<UserInfoDTO> USER_THREAD_LOCAL = new TransmittableThreadLocal<>();

    // 初始化TTL的Executor包装
    public static Executor getTtlExecutor(Executor executor) {
        return TtlExecutors.getTtlExecutor(executor);
    }

    // 包装Runnable
    public static Runnable ttlRunnable(Runnable runnable) {
        return TtlRunnable.get(runnable);
    }

    // 包装Callable
    public static <T> Callable<T> ttlCallable(Callable<T> callable) {
        return TtlCallable.get(callable);
    }

    // 原有方法保持不变
    public static void setUser(UserInfoDTO user) {
        USER_THREAD_LOCAL.set(user);
    }

    public static Integer getUserId() {
        UserInfoDTO userInfoDTO = USER_THREAD_LOCAL.get();
        return Optional.ofNullable(userInfoDTO).map(UserInfoDTO::getUserId).orElse(null);
    }

    public static String getUsername() {
        UserInfoDTO userInfoDTO = USER_THREAD_LOCAL.get();
        return Optional.ofNullable(userInfoDTO).map(UserInfoDTO::getUsername).orElse(null);
    }

    public static void removeUser() {
        USER_THREAD_LOCAL.remove();
    }
    // 获取用户上下文副本（用于跨线程传递）
    public static UserInfoDTO getUserCopy() {
        UserInfoDTO original = USER_THREAD_LOCAL.get();
        System.out.println("麻麻列别杀:   " + original);
        if (original == null) return null;
        // 需要实现深拷贝
        return UserInfoDTO.builder()
                .userId(original.getUserId())
                .username(original.getUsername())
                .build();
    }

}
